<template>
  <div class="upload-container">
    <el-button class="editor-video-btn" size="mini" plain type="primary" @click="opendialog">上传视频</el-button>
    <el-dialog v-model="dialogVisible" destroy-on-close title="上传视频">
      <input
        :disabled="initData.videoTips.length > 0"
        type="file"
        name="file"
        class="imageFile"
        accept="video/*"
        @change="postVideo($event)"
      />
      <div class="button-content">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">上传</el-button>
      </div>
      <div v-if="initData.videoTips && initData.videoTips.length" class="video-tips">
        <p v-for="tips in initData.videoTips" :key="tips.time" class="video-tip">{{ tips.content }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, defineEmits, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { deepCopy } from '@/utils/util'
import { createUploader, getVideoMes, getVideoTaskStatus, creatingVideoTranscoding } from '@/api/video'

const props = defineProps({
  color: {
    type: String,
    default: '#1890ff'
  }
})
const initData = reactive({
  videoContent: {
    id: '', // 视频id
    name: '', // 视频名称
    coverUrl: '', // 视频封面
    duration: '', // 视频时长
    sourceVideoUrl: '', // 视频播放地址
    time: '', // 时间戳
    vodTaskId: '', // 任务id
    vodTaskStatus: '', // 任务是否结束
    vodSize: '',
    vodType: ''
  },
  videoTips: [] as any,
  timeId: '' as any
})
const dialogVisible = ref(false)
const timer = ref()
// 打开弹窗
const opendialog = () => {
  dialogVisible.value = true
  initData.videoContent = Object.assign(initData.videoContent, {
    id: '', // 视频id
    name: '', // 视频名称
    coverUrl: '', // 视频封面
    duration: '', // 视频时长
    sourceVideoUrl: '', // 视频播放地址
    time: '', // 时间戳
    vodTaskId: '', // 任务id
    vodTaskStatus: '', // 任务是否结束
    vodSize: '',
    vodType: ''
  })
  initData.videoTips = []
  clearInterval(timer.value)
}
// 上传视频
const postVideo = (e) => {
  const data = e.target.files
  const me = this
  if (!(data[0].name.indexOf('.mp4') > -1 || data[0].name.indexOf('.MP4') > -1)) {
    ElMessage.error('视频格式不是mp4')
    return
  }
  clearInterval(timer.value)
  const timeId = Date.parse(new Date())
  initData.timeId = timeId
  const videoContent = deepCopy(initData.videoContent)
  initData.videoTips.push({
    time: timeId,
    name: data[0].name,
    content: `视频文件名${data[0].name},正在上传中`
  })
  videoContent.time = timeId
  const num = initData.videoTips.findIndex((_) => {
    return _.time === timeId
  })

  return createUploader
    .call(me, data[0])
    .then((result = {}) => {
      videoContent.id = result.videoId
      const task = function () {
        creatingVideoTranscoding(result.videoId)
          .then(function (res) {
            if (res.data.code === 0) {
              // 兼容接口转码信息未及时获取到
              if (res.data.data === -1) {
                return setTimeout(() => {
                  task()
                }, 3000)
              }
              videoContent.name = data[0].name
              videoContent.vodTaskId = res.data.data
              videoContent.vodTaskStatus = 'WAITING'
              initData.videoContent = videoContent
              initData.videoTips[num].content = `上传成功，视频文件名${data[0].name},正在转码中`
              timer.value = setInterval(() => {
                handleSubmit()
              }, 5000)
            } else {
              delVideoTips(timeId)
              clearInterval(timer.value)
              ElMessage.error(`${data[0].name}视频上传失败，请删除后重新上传`)
            }
          })
          .catch((_) => {
            delVideoTips(timeId)
            clearInterval(timer.value)
            ElMessage.error(`${data[0].name}视频上传失败，请删除后重新上传`)
          })
      }
      task()
    })
    .catch((_) => {
      clearInterval(timer.value)
    })
}

// 提交数据
const handleSubmit = () => {
  clearInterval(timer.value)
  if (initData.videoContent.vodTaskStatus !== 'CompleteAllSucc') {
    if (!initData.videoContent.vodTaskId) {
      return
    }
    getVideoTaskStatus(initData.videoContent.vodTaskId)
      .then(function (res) {
        initData.videoContent.vodTaskStatus = res.data.data
        if (res.data.data === 'CompleteAllSucc') {
          getVideoContent()
        } else {
          addVideoTips(initData.timeId, initData.videoContent.name)
        }
      })
      .catch((err) => {
        clearInterval(timer.value)
        ElMessage.error(err.message || '视频转码失败，请删除后重新上传')
      })
    return
  }
  if (initData.videoContent.vodTaskStatus === 'CompleteAllSucc' && initData.videoContent.coverUrl === '') {
    getVideoContent()
  }
}

// 获取视频
const getVideoContent = () => {
  getVideoMes(initData.videoContent.id)
    .then(function (data) {
      if (data.data.code === 0 && data.data.data !== null) {
        initData.videoContent.duration = data.data.data.duration
        initData.videoContent.sourceVideoUrl = data.data.data.sourceVideoUrl
        initData.videoContent.coverUrl = data.data.data.coverUrl
        initData.videoContent.vodSize = data.data.data.mSize
        initData.videoContent.vodType = `${data.data.data.height}x${data.data.data.width}`
        delVideoTips(initData.videoContent.time)
        pushContent()
      } else {
        setTimeout(function () {
          getVideoMes(initData.videoContent)
        }, 4000)
      }
    })
    .catch((err) => {
      clearInterval(timer.value)
      ElMessage.error(err.message || '视频获取失败，请删除后重新上传')
    })
}

//  添加videoTips
const addVideoTips = (id, name) => {
  let num = 0
  initData.videoTips.map(function (value, index) {
    if (parseInt(id) === parseInt(value.time)) {
      num++
    }
  })
  if (num === 0) {
    initData.videoTips.push({
      time: id,
      name: name,
      content: `视频文件名${name},正在转码中`
    })
  }
}

// 删除videoTips
const delVideoTips = (id) => {
  initData.videoTips.map(function (value, index) {
    if (parseInt(id) === parseInt(value.time) || value.status === undefined) {
      initData.videoTips.splice(index, 1)
    }
  })
}
// 关闭弹窗
const close = () => {
  dialogVisible.value = false
}

const emits = defineEmits(['VideosuccessCBK'])

const pushContent = () => {
  const videoinfo = initData.videoContent
  const addData = {
    img: videoinfo.coverUrl || '', // 视频图片或图片
    link: videoinfo.sourceVideoUrl || '', // 外链或视频播放地址
    id: videoinfo.id || '', // 视频id
    duration: videoinfo.duration || '', // 播放时长
    vodSize: videoinfo.vodSize || '', // 视频宽高
    vodType: videoinfo.vodType || '' // 视频大小
  }
  clearInterval(timer.value)
  emits('VideosuccessCBK', addData)
  close()
}
onUnmounted(() => {
  clearInterval(timer.value)
})
</script>

<style lang="scss" scoped>
.button-content {
  margin: 20px 0;
}

.editor-video-btn {
  position: absolute;
  top: 22px;
  right: 4px;
  z-index: 1003;
}
</style>
